package com.huluobo.lc.ppjoke_jetpack.ui;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;
import androidx.paging.PagedList;
import androidx.paging.PagedListAdapter;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.huluobo.lc.libcommon.EmptyView;
import com.huluobo.lc.ppjoke_jetpack.R;
import com.huluobo.lc.ppjoke_jetpack.databinding.LayoutRefreshViewBinding;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * @author Lc
 * @description: 列表fragment的基类
 * @date :2020/7/17 10:23
 */
public abstract class AbsListFragment<T, M extends AbsViewModel<T>> extends Fragment implements OnRefreshListener, OnLoadMoreListener {
    private LayoutRefreshViewBinding binding;
    private RecyclerView recyclerView;
    private SmartRefreshLayout smartRefreshLayout;
    private EmptyView emptyView;
    private PagedListAdapter<T, RecyclerView.ViewHolder> adapter;
    private M viewModel;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        binding = LayoutRefreshViewBinding.inflate(inflater, container, false);
        recyclerView = binding.recyclerView;
        smartRefreshLayout = binding.refreshLayout;
        emptyView = binding.emptyView;

        smartRefreshLayout.setEnableRefresh(true);
        smartRefreshLayout.setEnableLoadMore(true);
        smartRefreshLayout.setOnRefreshListener(this);
        smartRefreshLayout.setOnLoadMoreListener(this);

        adapter = getAdapter();
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext(),
                LinearLayoutManager.VERTICAL, false));
        recyclerView.setItemAnimator(null);
        DividerItemDecoration decoration = new DividerItemDecoration(getContext(),
                LinearLayoutManager.VERTICAL);
        decoration.setDrawable(ContextCompat.getDrawable(getContext(), R.drawable.list_divider));
        recyclerView.addItemDecoration(decoration);
        afterCreateView();
        return binding.getRoot();
    }

    protected abstract void afterCreateView();

    public abstract PagedListAdapter<T, RecyclerView.ViewHolder> getAdapter();

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
        Type[] actualTypeArguments = type.getActualTypeArguments();
        if (actualTypeArguments.length > 1) {
            Type argument = actualTypeArguments[1];
            Class modelClaz = ((Class) argument).asSubclass(AbsViewModel.class);
            viewModel = (M) ViewModelProviders.of(this).get(modelClaz);
            viewModel.getPageData().observe(getViewLifecycleOwner(), new Observer<PagedList<T>>() {
                @Override
                public void onChanged(PagedList<T> pagedList) {
                    adapter.submitList(pagedList);
                }
            });
            viewModel.getBoundaryPageData().observe(getViewLifecycleOwner(),
                    new Observer<Boolean>() {
                @Override
                public void onChanged(Boolean hasData) {
                    //监听页面上是否有数据,来控制空页面的加载
                    finishRefresh(hasData);
                }
            });
        }
    }

    //通过是否有数据来关闭下拉刷新或者上拉加载
    public void finishRefresh(boolean hasData) {
        PagedList<T> currentList = adapter.getCurrentList();//列表中当前的集合
        hasData = hasData || currentList != null && currentList.size() > 0;
        RefreshState state = smartRefreshLayout.getState();//获取下来框架的状态
        if (state.isFooter && state.isOpening) {
            smartRefreshLayout.finishLoadMore();
        } else if (state.isHeader && state.isOpening) {
            smartRefreshLayout.finishRefresh();
        }

        if (hasData) {
            emptyView.setVisibility(View.GONE);
        } else {
            emptyView.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 为adapter中的list添加数据
     *
     * @param pagedList 每次下拉刷新通过paging框架拿到的list
     */
    public void submitList(PagedList<T> pagedList) {
        if (pagedList.size() > 0) {
            adapter.submitList(pagedList);
        }
        finishRefresh(pagedList.size() > 0);
    }
}
